<?php

namespace app\api\controller;

use app\admin\model\UserCourse;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;
use think\Db;
use app\admin\model\Bmi;
use app\admin\model\Course;
use app\admin\model\Order;
use app\common\model\Wechat;
/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['authorizedLogin','getToken','register','getOpenId','getPhoneNumber'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /*
     *获取用户登录token
     * */
    public function getToken()
    {
        $openid = $this->request->param('code');
        $user = \app\common\model\User::where('openid', $openid)->find();
        $this->auth->direct($user['id']);
        $data = $this->auth->getUserinfo();
        $this->success('',  $data);
    }
    /*
     * 解析获取openId
     * */
    public function getOpenId()
    {
        $this->checkParam('code');
        $code = $this->request->param('code');
        $openid = Wechat::getOpenId($code);
        if (!isset($openid['openid'])) {
            $this->error('openid获取失败',$openid);
        }
        $user = \app\common\model\User::where('openid', $openid['openid'])->find();
       // $user = \app\common\model\User::where('openid', $code)->find();

        if ($user) {
            $this->auth->direct($user['id']);
            $data = $this->auth->getUserinfo();
            if (!empty($data['venue_id'])) {
                $data['info'] = true;
            } else {
                $data['info'] = false;
            }
            $bmi = Bmi::where('user_id', $user['id'])->find();
            if ($bmi) {
                $data['bmi'] = true;
            } else {
                $data['bmi'] = false;
            }
            $this->success('', ['openId' => $openid, 'user' => $data]);
        } else {
            $this->success('', ['openId' => $openid]);
        }

    }

    /*小程序授权获取手机号*/
    public function getPhoneNumber($code)
    {
        $ret = Wechat::getPhone($code);
        if ($ret['errcode'] != 0) {
            $this->error($ret);
        } else {
            $this->success('请求成功', $ret['phone_info']);
        }

    }

    public function register()
    {
        $nickname = $this->request->post('nickname');
        $openid = $this->request->post('openid');
        $mobile = $this->request->post('mobile');
        $user = \app\common\model\User::where('openid', $openid)->find();
        if ($user) {
            $user->nickname = $nickname;
            $user->mobile = $mobile;
            $user->save();
            $this->auth->direct($user['id']);
        } else {
            $avatar = cdnurl('/uploads/20220214/d3a9bfc75ee8baeed05b84f6f853c68e.png', true);
            $ret = $this->auth->register($nickname, '', '', $mobile, ['openid' => $openid, 'avatar' => $avatar]);
           // $ret = $this->auth->register($nickname, '', '', $mobile, ['openid' => $openid]);
            if (!$ret) {
                $this->error($this->auth->getError());
            }
        }
        $this->success('注册成功',  $this->auth->getUserinfo());
        /*if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }*/
    }

    /*
     * 用户初始数据
     *
     * */
    public function saveInfo()
    {
        $this->checkParam(['username','gender','age','birthday','location','school','venue_id']);
        $param = $this->request->post();
        $uid = $this->auth->id;
        $ret = \app\common\model\User::where('id', $uid)->update($param);
        /*$gender = $this->request->post('gender');
        $age = $this->request->post('age');
        $birthday = $this->request->post('birthday');
        $location = $this->request->post('location');
        $school = $this->request->post('school');
        $venue_id = $this->request->post('venue_id');*/
        if ($ret) {
            $this->success('保存成功');
        } else {
            $this->error('保存失败');
        }

    }

    /*
     *
     * 判断是否注册过
     * */
    public function isRegister()
    {
        $this->checkParam('openid');
        $openId = $this->request->request('openid');
        $ret = Db::name('user')->where('openid', $openId)->find();
        if ($ret) {
            $this->success(__('已注册'));
        } else {
            $this->error(__('未注册'));
        }

    }

    /*
     *
     *保存原始bmi值
     * */
    public function  saveBMI()
    {
        $this->checkParam(['height','weight','vital_capacity','arm_span','flexibility','s_flexibility','medical_history', 'remarks']);
        $data = $this->request->post();
        $data['time'] = time();
        $this->checkParam(['uid']);
        $data['user_id'] = $this->request->request('uid');
        $ret = Bmi::insert($data);
        if ($ret) {
            $this->success(__('保存成功'));
        } else {
            $this->error(__('保存失败，请稍后再试'));
        }

    }

    /*
     * 读取最新的BMI值
     *
     * */
    public function getBMI()
    {
        $this->checkParam(['uid']);
        $uid = $this->request->request('uid');
        $page = $this->request->request('page');
        $pagesize = $this->request->request('pagesize');

       // $ret = Bmi::where('user_id', $uid)->limit(1)->order("id desc")->select();

        $list = Bmi::where('user_id', $uid)->order("id desc")->paginate($pagesize, $simple = false, $config = [$page])->toArray();
        /*$list = $this->model
            ->with(['venue'])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);*/
/*        if ($list['data']) {
            foreach ($list['data'] as &$v) {

            }
        }*/

        $this->success(__('BMI数据'), $list);

    }

    /*
     *
     * 获取用户信息
     * */
    public function getUserInfo()
    {
        $this->checkParam(['uid']);
        $uid = $this->request->request('uid');
        //$ret = Db::name('user')->where('id', $uid)->column('id,nickname,avatar,age,gender,mobile,money');
        $ret =  Db::name('user')->where('id',$uid)->field('id,nickname,avatar,age,gender,mobile,money,mobile as phone, birthday')->find();
        /*if( !$ret['avatar'] ) {
            $ret['avatar'] = letter_avatar($ret['nickname']);
        }*/
        $this->success(__('用户基本信息'), $ret);

    }

    /*
     *
     * 我的身份账户
     * */
    public function myAccount()
    {
        $uid = $this->auth->id;
        $ret = \app\common\model\User::where('id', $uid)->whereOr('pid', $uid)->field('id,username')->select();
        $this->success(__('身份列表'), $ret);
    }

    /*
     *
     * 绑定/编辑子账户
     * */
    public function addAccount()
    {
        $uid = $this->auth->id;
        $id = $this->request->request('id');
        if ($this->request->isGet()) {
            $id = $this->request->request('id');

            $this->success(__('身份信息'),Db::name('user')->where('id', $id)->field('username,birthday,age,gender,location,school')->find());
        }
        if ($this->request->isPost()) {
            $this->checkParam(['username','gender','age','birthday','location','school']);
            $user = \app\common\model\User::where('id', $uid)->find();
            $data = $this->request->post();
            
            if (isset($data['id'])) {
                //修改身份信息
                \app\common\model\User::where('id', $data['id'])->update($data);
                $this->success(__('修改成功'));
            } else {
                $data['venue_id'] = $user['venue_id'];
                $data['pid'] = $uid;
                
                //绑定新身份
                $username = $this->request->post('username');
                $ret = $this->auth->register($username, '', '', '', $data);
                if ($ret) {
                    $this->success(__('绑定成功'));
                } else {
                    $this->error($this->auth->getError());
                }
            }
        }
        

    }

    /*
     * 我的预约
     * */
    public function plan()
    {
        $uid = $this->auth->id;
        $users = \app\common\model\User::where('id', $uid)->whereOr('pid', $uid)->column('id');
        $list = Db::table('keep_user_course')
            ->alias('u')
            ->join('keep_course c','c.id = u.course_id','left')
            ->join('keep_term t','t.id = u.term_id','left')
            ->join('keep_user user', 'u.user_id = user.id')
            ->join('keep_time m', 't.time_id = m.id')
            ->whereIn('u.user_id',$users)
            ->where('u.type','1')
            ->where('u.status','0')
            ->field(' u.id as plan_id,u.course_id, c.name as courseName, c.image, user.username as userName, t.stime as date,  m.stime, m.etime')
            ->select()
            ->toArray();
        if ($list) {
            foreach ($list as &$v) {
                $v['image'] = cdnurl($v['image'], true);
            }
        }
        $this->success('课程预约', $list);
    }

    /*
     * 预约详情
     * */
    public function planInfo()
    {
        $this->checkParam(['id']);
        $uid = $this->auth->id;
        $plan_id = $this->request->request('id');
        $users = \app\common\model\User::where('id', $uid)->whereOr('pid', $uid)->column('id');
        $userCourse = UserCourse::where('id', $plan_id)->whereIn('user_id', $users)->find();
        if (!$userCourse) {
            $this->error('暂无预约');
        }

        $info = Db::table('keep_user_course')
            ->alias('u')
            ->join('keep_course c','c.id = u.course_id','left')
            ->join('keep_term t','t.id = u.term_id','left')
            ->join('keep_user user', 'u.user_id = user.id')
            ->join('keep_user user2', 't.user_id = user2.id')
            ->join('keep_time m', 't.time_id = m.id')
            ->whereIn('u.id',$plan_id)
            ->field(' u.id as plan_id,
                    u.course_id,
                    c.name as courseName,
                    c.type,
                    c.image,c.describe, 
                    c.venue_id,
                    user.username as userName,
                    user2.username as coachName, 
                    user.avatar as userImage, 
                    user2.image as coachImage, 
                    user.profile as userProfile, 
                    user2.profile as coachProfile, 
                    user2.label,
                    user2.star,
                    t.stime as sdate,  
                    t.etime as edate,  
                    m.stime, 
                    m.etime')
            ->find();
        if ($info['type'] == 3) {
            $this->error('团体课不支持自己预约，请联系售后');
        }
        if ( $info) {
            $info['image'] = cdnurl($info['image'], true);
            $info['coachImage'] = cdnurl($info['coachImage'], true);

            $info['venue'] = Db::name('venue')->where('id', $info['venue_id'])->field('id,name,address,latitude,longitude')->find();
        }
        $this->success('课程预约详情', $info);
    }

    /*
     *
     * 取消预约
     * */
    public function changePlan()
    {
        $this->checkParam(['id']);
        $uid = $this->auth->id;
        $plan_id = $this->request->request('id');

        $users = \app\common\model\User::where('id', $uid)->whereOr('pid', $uid)->column('id');
        $userCourse = UserCourse::where('id', $plan_id)->whereIn('user_id', $users)->where('type', '1')->find();
        if (!$userCourse) {
            $this->error('暂无预约可取消');
        }

        $type = Course::where('id', $userCourse['course_id'])->column('type');
        if ($type == 3) {
            $this->error('团体课无法自己取消，取消请联系售后');
        }

        $info = Db::table('keep_user_course')
            ->alias('u')
            ->join('keep_term t','t.id = u.term_id','left')
            ->whereIn('u.id',$plan_id)
            ->field('t.stime as date')
            ->find();
        //判断日期时间戳的大小，跟时间点的时间戳大小
        if (strtotime($info['date'] ) < strtotime(date('Y-m-d',time())) ) {
            $this->error('取消失败，开课前一天才能取消');
        }

        UserCourse::where('id', $plan_id)->update(['type'=> 0]);
        $this->success('预约取消成功');
    }
    
    /*
     * 用户订单
     * */
    public function orderList()
    {
        $this->checkParam(['status']);

        $uid = $this->auth->id;
        $status = $this->request->request('status');
        $db = Db::table('keep_order')
            ->alias('o')
            ->join('keep_course c','c.id = o.course_id','left')
            ->join('keep_user_course', '"o.order_no" = "keep_user_course.order_no"','left')
            ->join('keep_venue v','c.venue_id = v.id','left')
            ->where('o.status', $status)
            ->where('o.user_id', $uid);
        if ($status == 0){
            $db->where('o.type','0');
        }

        $orderList =  $db->field("o.order_no,
                     o.snapshot,
                     o.price,
                     o.ctime,
                     o.type as orderType,
                     o.ptime,
                     o.course_id,
                     c.name as courseName,
                     c.day,
                     c.image,
                     keep_user_course.id as plan_id,
                     keep_user_course.type as courseStatus,
                     v.name as venueName")
            ->select()
            ->toArray();
        //修改过期订单
        if ($orderList) {
            foreach ($orderList as &$v){
                $v['image'] = cdnurl($v['image'], true);

                $v['expir_time'] = $v['ctime'] + 60*60*2;
                if ($status==0 && (time() - $v['ctime']) > 60*60*2){
                    Order::where('order_no', $v['order_no'])->update(['status' => 2]);
                    unset($v);
                }

            }
        }


        $this->success('订单列表',$orderList);

    }

    public function coursePlan()
    {
        $this->checkParam('uid');
        $user_id = $this->request->request('uid');
        /*$uid  = $this->auth->id;
        $users = \app\common\model\User::where('id', $uid)->whereOr('pid', $uid)->column('id');*/
        $list = Db::table('keep_user_course')
            ->alias('t')
            ->join('keep_course c','c.id = t.course_id','left')
            ->join('keep_venue v','v.id = t.venue_id','left')
            ->join('keep_user u','u.id = t.user_id','left')
            ->join('keep_term term','term.id = t.term_id','left')
            ->join('keep_time time','time.id = term.time_id','left')
            ->where('t.user_id',$user_id)
            ->where('t.type','2')
            ->field('t.id as plan_id, v.name as venueName,c.id as course_id, c.name as courseName,  c.day,c.image,c.type, term.stime as date, time.stime, u.username')
            ->select()
            ->toArray();
        $list1 = Db::table('keep_user_course')
            ->alias('t')
            ->join('keep_course c','c.id = t.course_id','left')
            ->join('keep_venue v','v.id = t.venue_id','left')
            ->join('keep_user u','u.id = t.user_id','left')
            ->join('keep_term term','term.id = t.term_id','left')
            ->join('keep_time time','time.id = term.time_id','left')
            ->where('t.user_id',$user_id)
            ->where('t.type','1')
            ->field('t.id as plan_id, v.name as venueName,c.id as course_id, c.name as courseName,  c.day,c.image,c.type, term.stime as date, time.stime, u.username')
            ->select()
            ->toArray();
        $list2 = Db::table('keep_user_course')
            ->alias('t')
            ->join('keep_course c','c.id = t.course_id','left')
            ->join('keep_venue v','v.id = t.venue_id','left')
            ->join('keep_user u','u.id = t.user_id','left')
            ->join('keep_term term','term.id = t.term_id','left')
            ->join('keep_time time','time.id = term.time_id','left')
            ->where('t.user_id',$user_id)
            ->where('t.type','3')
            ->field('t.id as plan_id, v.name as venueName,c.id as course_id, c.name as courseName,  c.day,c.image,c.type, term.stime as date, time.stime, u.username')
            ->select()
            ->toArray();
        $lista = array_merge($list,$list1,$list2);
        if ($lista) {
            foreach ($lista as &$v) {
                $v['image'] = cdnurl($v['image'], true);
            }
        }
        $this->success('课程计划', $lista);
    }

    /*
     *
     * 课程内容
     * */
    public function planContent()
    {
        $this->checkParam('id');
        $plan_id = $this->request->request('id');

        $userCourse = Db::table('keep_user_course')->where('id', $plan_id)->find();


        $list = Db::table('keep_course_plan')
            ->where('course_id', $userCourse['course_id'])
            ->field('id as content_id,name,image')
            ->select()
            ->toArray();

        if ($list) {
            foreach ($list as &$v) {
                $v['image'] = cdnurl($v['image'], true);
                $v['user_plan'] = Db::name('user_course_plan')->where('course_plan_id', $v['content_id'])->where('user_id', $userCourse['user_id'])->where('term_id', $userCourse['term_id'])->find();
            }
        }
        $this->success('课程计划', $list);
    }

    /*
     * 获取课程的细节
     * */
    public function courseNode()
    {
        $this->checkParam('id', 'content_id');
        $plan_id = $this->request->request('id');
        $content_id = $this->request->request('content_id');
        $userCourse = Db::table('keep_user_course')->where('id', $plan_id)->find();

        $list = Db::table('keep_course_node')
            ->where('course_id', $userCourse['course_id'])
            ->where('course_plan_id', $content_id)
            ->field('id as node_id,name')
            ->select()
            ->toArray();

        if ($list) {
            foreach ($list as &$v) {
                $v['user_node'] = Db::name('user_course_node')->where('course_id', $content_id)->where('course_node_id', $v['node_id'])->where('user_id', $userCourse['user_id'])->where('term_id', $userCourse['term_id'])->find();
            }
        }
      //  $list['plan_id'] = $plan_id;
        $this->success('课程计划', $list);
    }

    public function wxMsg()
    {
        $uid = $this->auth->id;
        $old = Db::name('user')->where('id',$uid)->value('wx_msg');
        $now = $old == 0 ? 1 : 0;
        $ret = Db::name('user')->where('id',$uid)->update(['wx_msg' => $now]);

        if ($ret) {
            $this->success('修改成功');
        } else {
            $this->error('修改失败');
        }
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function registerAA()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
       // $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        //$bio = $this->request->post('bio');
        $gender = $this->request->post('gender');
        $age = $this->request->post('age');
        $phone = $this->request->post('phone');
      //  $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        $avatar = $this->request->post('avatar');
        $birthday = $this->request->post('birthday');
       /* if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }*/
        if ($nickname) {
            $data['nickname']= $nickname;
        }
        if ($birthday) {
            $data['birthday'] = $birthday;
        }
        if ($age) {
            $data['age'] = $age;
        }
        if ($phone) {
            $exists = \app\common\model\User::where('mobile', $phone)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('手机号已存在'));
            }
            $data['mobile'] = $phone;
        }
        if ($gender) {
            $data['gender'] = $gender;
        }
        if ($avatar) {
            $data['avatar'] = $avatar;
        }

        $ret = Db::name('user')->where('id',  $this->auth->id)->update($data);
        if ($ret) {
            $this->success('修改成功');
        } else {
            $this->error(__('修改失败'),$ret);
        }

    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
}
